After delaying a lot, I have started working on Data Visualization
with R (Thanks to Anton for
introducing me to R). I am starting with Scatter Plot (generally what I
use most of the time).
The script and data is mainly taken from r-graph-gallery.
library(tidyverse)
library(plotly)
library(htmlwidgets) #to save html file
Let’s start with a basic scatter plot.
# Keep 30 first rows in the mtcars natively available data set
data=head(mtcars, 30)
# 1/ add text with geom_text, use nudge to nudge the text
p <- ggplot(data, aes(x=wt, y=mpg)) +
geom_point(color="orange", fill="#69b3a2", shape=21, alpha=0.5, size=6,
stroke = 1) + # Show dots
theme(axis.text.x = element_text(color = "grey20", size = 18),
axis.text.y = element_text(color = "grey20", size = 18),
axis.title.x = element_text(color = "grey20", size = 18),
axis.title.y = element_text(color = "grey20", size = 18),
plot.title = element_text(size = 18)) +
xlab("X-axis Data ") +
ylab("Y-axis Data") +
ggtitle("Basic Plot") +
geom_text(label=rownames(data), nudge_x = 0.25,
nudge_y = 0.25, check_overlap = T)
p
Instead of geom_text(), let’s use geom_label().
# Keep 30 first rows in the mtcars natively available dataset
data <- head(mtcars, 30)
# Change data rownames as a real column called 'car Name'
data <- data %>% rownames_to_column(var="carName")
# Plot
p <- ggplot(data, aes(x=wt, y=mpg)) +
geom_point() +
geom_label( data=data %>% filter(mpg>20 & wt>3), aes(label=carName))
p
Let’s write some random text!
# Keep 30 first rows in the mtcars natively available dataset
data=head(mtcars, 30)
# Add one annotation
ggplot(data, aes(x=wt, y=mpg)) +
geom_point() + # Show dots
geom_label(label="Look at this!", x=4.1, y=21,
label.padding = unit(0.55, "lines"), # Rectangle size around labels
label.size = 0.35, color = "black", fill="#69b3a2")
Now let’s make an interactive scatter plot. For this, we have to use plotly. i have mainly followed this video by Sarah Lucas and Pat Schloss.
# Keep 30 first rows in the mtcars natively available data set
data = head(mtcars, 50)
# 1/ add text with geom_text, use nudge to nudge the text
p <- ggplot(data, aes(x=wt, y=mpg, color=qsec, size=qsec, text=paste0("disp: ", disp,"\n","HorsePower: ", hp))) +
geom_point() +
theme(axis.text.x = element_text(color = "grey20", size = 18),
axis.text.y = element_text(color = "grey20", size = 18),
axis.title.x = element_text(color = "grey20", size = 18),
axis.title.y = element_text(color = "grey20", size = 18)) +
xlab("X-axis Data: wt ") +
ylab("Y-axis Data: mpg")
p1 <- ggplotly(p, tooltip = "text")
p1